package com.lanou.lenanapp.adapter;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.graphics.Movie;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.lanou.lenanapp.R;
import com.lanou.lenanapp.activity.LargeImageActivity;
import com.lanou.lenanapp.activity.ReviewActivity;
import com.lanou.lenanapp.db.DatabaseHelper;
import com.lanou.lenanapp.entity.greendao.CollectImageEntity;
import com.lanou.lenanapp.entity.greendao.ImageEntity;
import com.lanou.lenanapp.view.GifMovieView;
import com.lanou.lenanapp.volley.StreamRequest;
import com.lanou.lenanapp.volley.VolleySingleton;


import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


public class ImageFragmentAdapter extends RecyclerView.Adapter<ImageFragmentAdapter.ImageViewHolder> {

    private List<ImageEntity> items;//趣图的实体类
    private List<CollectImageEntity> collectImageEntities;

    VolleySingleton volleySingleton = VolleySingleton.getInstance();
    private ImageLoader imageLoader;
    private DatabaseHelper helper;
    private Context context;


    public ImageFragmentAdapter(Context context){
        this.context = context;
        //初始化
        imageLoader = volleySingleton.getImageLoader();
    }

    public void loadData(List<ImageEntity> datas){
        this.items.addAll(datas);
        notifyDataSetChanged();
    }


    public void addData(List<ImageEntity> datas){
        this.items = datas;
        notifyDataSetChanged();
    }


    /**
     * 组件缓存内部类
     * **/
    class ImageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        private TextView updata_time_image, wbody_image, comments_image, like_image;
        private ImageView like_one_image, like_image_image, favorited_collect_image;
        private NetworkImageView imageIv;
        private GifMovieView gifMovieView;
        private int position;
        private int size;


        public ImageViewHolder(View itemView) {
            super(itemView);
            helper = DatabaseHelper.getHelper();
            updata_time_image = (TextView) itemView.findViewById(R.id.updata_time_image);
            wbody_image = (TextView) itemView.findViewById(R.id.wbody_image);
            comments_image = (TextView) itemView.findViewById(R.id.comments_image);
            imageIv = (NetworkImageView) itemView.findViewById(R.id.imageIv);
            gifMovieView = (GifMovieView) itemView.findViewById(R.id.gifMovieView);
            like_one_image = (ImageView) itemView.findViewById(R.id.like_one_image);
            like_image_image = (ImageView) itemView.findViewById(R.id.like_image_image);
            like_image = (TextView) itemView.findViewById(R.id.like_image);
            favorited_collect_image = (ImageView) itemView.findViewById(R.id.favorited_collect_image);
            favorited_collect_image.setOnClickListener(this);
            like_image_image.setOnClickListener(this);
            comments_image.setOnClickListener(this);
            imageIv.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.comments_image:
                    //评论按钮跳转到评论界面
                    if(items != null && items.size() > 0){
                        ImageEntity im = items.get(position);//先获取位置
                        Intent intent = new Intent(context, ReviewActivity.class);
                        intent.putExtra("id", im.getWid());//将wid属性传过去 拼接网址
                        context.startActivity(intent);
                    }
                    break;
                case R.id.imageIv:
                        //点击图片跳转到只有图片的界面
                        ImageEntity imm = items.get(position);
                        Intent intent = new Intent(context, LargeImageActivity.class);
                        //将大图片地址传过去
                        intent.putExtra("image", imm.getWpic_large());
                        context.startActivity(intent );
                    break;
                case R.id.like_image_image://点赞
                    ImageEntity imageEntity = items.get(position);
                    int t = imageEntity.getIsChange();
                    if (t == 0){
                        t = t + 1;
                        imageEntity.setIsChange(t);
                        //点击换图片
                        like_image_image.setImageResource(R.drawable.icon_liked);
                        like_one_image.setVisibility(View.VISIBLE);
                        startAnim();//播放赞动画
                        double d = Double.parseDouble(imageEntity.getLikes());
                        int tt = (int) d;
                        tt++;
                        like_image.setText(tt + "");
                        imageEntity.setLikes(tt + "");
                    }else{
                        Toast.makeText(context, "您已经赞过了..", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case R.id.favorited_collect_image://收藏按钮
                    ImageEntity i = items.get(position);
                    int isChange  = i.getIsChange();
                    if (isChange == 0) {
                        CollectImageEntity entity = new CollectImageEntity(null, i.getWid(), i.getUpdate_time(), i.getWbody(), i.getComments(), i.getLikes(), i.getIs_gif(), i.getWpic_small(), i.getWpic_middle(),i.getWpic_large(), i.getW_sensitive());
                        helper.saveCollectImageList(entity);
                        Toast.makeText(context, "收藏成功..快去看看吧", Toast.LENGTH_SHORT).show();
                        favorited_collect_image.setImageResource(R.drawable.icon_favorited);

                        isChange = isChange + 1;
                        i.setIsChange(isChange);
                    }else if (isChange == 1){
                        long id = i.getId();
                        helper.deleteByIdCollectImage(id);
                        favorited_collect_image.setImageResource(R.drawable.icon_favorite);
                        Toast.makeText(context, "已经取消收藏..", Toast.LENGTH_SHORT).show();
                    }
                    break;
            }

        }


        /**
         * 播放赞的动画
         * **/
        private void startAnim() {
            ObjectAnimator animator = new ObjectAnimator().ofFloat(like_one_image, "scale", 1, 3, 4, 5);
            animator.setDuration(1000);
            animator.start();
            animator.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    super.onAnimationEnd(animation);
                    like_one_image.setVisibility(View.GONE);
                }
            });
        }
    }

    @Override
    public ImageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        //获得布局加载器
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        //加载行布局
        View v = inflater.inflate(R.layout.activity_fragment_image_gut, null);

        return new ImageViewHolder(v);
    }

    @Override
    public void onBindViewHolder(ImageViewHolder holder, int position) {
            if (items != null && items.size() > 0){
                holder.position = position;//给定义的position赋值 获取当前行布局对应的位置
                ImageEntity image = items.get(position);
                //时间转换
                String time = getNormalTime(image.getUpdate_time());
                holder.updata_time_image.setText(time);

                holder.wbody_image.setText(image.getWbody());
                //设置赞的数量(返回的赞的数据是小数的字符串)
                //先转换成double格式
                double d = Double.parseDouble(image.getLikes());
                int t = (int) d;//再强制转换成int类型(因为string不能直接转换成int类型)
                holder.like_image.setText(t + "");//在转换成字符串格式显示

                holder.comments_image.setText(image.getComments());

                int is = Integer.parseInt(image.getIs_gif());
                String url = image.getWpic_middle();
                if (is == 0) {
                    holder.gifMovieView.setVisibility(View.GONE);
                    holder.imageIv.setVisibility(View.VISIBLE);
                    //图片
                    getBitMap(url, holder.imageIv);
                }else if(is == 1){
                    holder.imageIv.setVisibility(View.GONE);
                    holder.gifMovieView.setVisibility(View.VISIBLE);
                    getGifMove(url, holder.gifMovieView);
                }
                //设置收藏按钮的图片
                int tt = image.getIsChange();
                if (tt == 0){
                    holder.favorited_collect_image.setImageResource(R.drawable.icon_favorite);
                }else if (tt == 1){
                    holder.favorited_collect_image.setImageResource(R.drawable.icon_favorited);
                }

                int ttt = image.getIsChange();
                if (ttt == 0){
                    holder.like_image_image.setImageResource(R.drawable.icon_like);
                }else {
                    holder.like_image_image.setImageResource(R.drawable.icon_liked);
                }


            }

    }


    /**
     * 时间格式转换方法
     * **/
    public  String  getNormalTime( String value) {
        Long l = Long.valueOf(value);
        l = l * 1000;
        Date date = new Date(l);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") ;
        String time = format.format(date) ;
        return time;
    }

    @Override
    public int getItemCount() {
        return items != null && items.size() > 0 ? items.size() : 0;
    }


    /** 拉取图片 **/
   private void getBitMap(String url, NetworkImageView imageView){
       imageView.setDefaultImageResId(R.mipmap.personal_image);
       imageView.setErrorImageResId(R.mipmap.lenan);
       imageView.setImageUrl(url, imageLoader);
    }

    /**
     * 动态图片的拉取
     * **/
    private void getGifMove(String url, final GifMovieView gifMovieView) {
        StreamRequest request = new StreamRequest(url, new Response.Listener<InputStream>() {
            @Override
            public void onResponse(InputStream response) {
                Movie movie = Movie.decodeStream(response);
                gifMovieView.setMovie(movie);
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });

        volleySingleton.addRequest(request);

    }





}
